package com.chang.search.thread;

import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * @author: changzhenxi
 * @date: 2024年11月06日 15:04
 * @Version: 1.0
 * @description: 线程组合方法测试 两个线程全部执行完毕之后再执行第三个
 */
public class ThreadBothTest {

    public static ExecutorService executor = Executors.newFixedThreadPool(10);

    public static void main(String[] args) throws ExecutionException, InterruptedException {

        CompletableFuture<Integer> future01 = CompletableFuture.supplyAsync(() -> {
            System.out.println("当前01线程启动::::" + Thread.currentThread().getId());
            int aaa = 777;
            System.out.println("当前01线程结束.....");
            return aaa;
        }, executor);


        CompletableFuture<String> future02 = CompletableFuture.supplyAsync(() -> {
            System.out.println("当前 02 线程启动::::" + Thread.currentThread().getId());
            return "goudan";
        }, executor);

        // runAfterBothAsync 等待另一个线程也执行完毕之后再执行第三个任务线程  无法获取之前两个线程的返回值
        // future01.runAfterBothAsync(future02,()->{System.out.println("当前03线程启动>>>>>>>");},executor);
        // thenAcceptBothAsync 可获取前面两个线程的执行结果 f1, f2就是两个个线程的返回结果也是第三个线程的参数
        // future01.thenAcceptBothAsync(future02, (f1, f2) -> {System.out.println("当前03线程启动>>>>>>>线程01的返回结果为>>"+f1+"<<<线程02返回结果:"+f2);},executor);
        // thenCombineAsync 即可获取两个线程的执行结果,也可以自己单独进行返回
        CompletableFuture<String> completableFuture = future01.thenCombineAsync(future02, (f1, f2) -> {
            return f1 + f2;
        }, executor);
        System.out.println("completableFuture.get() = " + completableFuture.get());

        // 多线程任务组合
        CompletableFuture.allOf(future01, future02).join();
    }
}
